package com.kit.lib;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.kit.ByteUtil;
import com.kit.CodecKit;

import org.apache.tomcat.util.buf.HexUtils;

/**
 * Aes加密工具类，密钥请见 接口文档，偏移量和密钥相同
 * 
 * @author Yuanqy
 * @Date 2019/07/05
 * @demo https://www.it399.com/aes
 * @company http://www.lianyuplus.com/
 */
public class AES {

	static String MODEL = "AES/CFB/NoPadding";
	static String ivs = "F1Y5HH4TI31ZUMDC"; // 偏移量
	static String key = "F1Y5HH4TI31ZUMDC"; // aes 密钥key ：must be 16

	// static String data = "1234567890123456";// 待加密数据
	static String data = "8E0372E64260457D6F9E8C6306CCE4";// 待加密数据

	public static void main(String[] args) throws Exception {

		byte[] pwd = encrypt(data.getBytes());
		System.out.println("密文长度[" + pwd.length + "]\t" + byte2hex(pwd));
		// byte[] res = decrypt(pwd);
		byte[] res = decrypt(ByteUtil.hex2byte(data));
		System.out.println("解密明文[" + res.length + "]\t" + byte2hex(res));
		System.out.println(CodecKit.encodeBase64(res));

	}

	/**
	 * 加密
	 */
	public static byte[] encrypt(byte[] src) {
		try {
			byte[] raw = key.getBytes();
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance(MODEL);
			IvParameterSpec iv = new IvParameterSpec(ivs.getBytes());
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
			return cipher.doFinal(src);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 解密
	 */
	public static byte[] decrypt(byte[] pwd) {
		try {
			byte[] raw = key.getBytes();
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance(MODEL);
			IvParameterSpec iv = new IvParameterSpec(ivs.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			return cipher.doFinal(pwd);
		} catch (Exception e) {
			return null;
		}
	}

	private static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + " " + "0" + stmp;
			else
				hs = hs + " " + stmp;
		}
		return hs.toUpperCase();
	}

}